<?php

namespace common\components;

use Yii;
use yii\helpers\ArrayHelper;
use RongCloud\RongCloud as RongCloudSdk;

class RongCloud extends \yii\base\Component {

    public $appKey;
    public $appSecret;

    public function getTransport() {
        return new RongCloudSdk($this->appKey, $this->appSecret);
    }

    /**
     * 推送
     * @return boolean
     */
    public function push($receiver, $message, $extra = null, $platform = ['ios', 'android']) {
        if (empty($receiver) || !$message) {
            Yii::error([
                '接收用户和消息内容不能为空',
                $receiver
            ], __METHOD__);
            return false;
        }
        $RongSDK = $this->getTransport();

        $all = false;
        if ($receiver === 'all') {
            $all = true;
        }
        $audience = [
            'is_to_all' => $all
        ];
        if (!$all && is_array($receiver)) {
            $audience = ArrayHelper::merge($audience, $receiver);
        }
        $notification = [
            'alert' => $message,
        ];
        if ($extra) {
            $notification['extra'] = $extra;
        }
        $sensitive = [
            'platform' => $platform, //目标操作系统
            'audience' => $audience, //推送条件，包括： tag、userid、is_to_all。
            'notification' => $notification
        ];
        $result = $RongSDK->getPush()->push($sensitive);
        $status = ArrayHelper::getValue($result, 'code');
        if ($status != 200) {
            Yii::error([
                '融云推送失败',
                $result
            ], __METHOD__);
            return false;
        }
        return true;
    }

}
